//
//  HomepageHeaderSectionView.swift
//  zhihuifan
//
//  Created by apple on 2017/8/29.
//  Copyright © 2017年 youyou. All rights reserved.
//

import UIKit
private let itemWith = ScreenWith/4
private let itemCout = 16

class HomepageHeaderSectionView: UIView {
    //父视图
    var contentOffY:CGFloat = -20.0
    

    @IBOutlet weak var scrollView: UIScrollView!
  class func loadNib() -> HomepageHeaderSectionView {
        let nib = UINib(nibName: "HomepageHeaderSectionView", bundle: nil)
        return (nib.instantiate(withOwner: nil, options: [:])[0] as? HomepageHeaderSectionView)!
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpUI()
    }
    //监听父视图
//    override func willMove(toSuperview newSuperview: UIView?) {
//        guard let sv = newSuperview as? UIScrollView else{
//            return
//        }
//        scrollView = sv
//        //kvo监听父视图的 contentoffset
//        //contentoffset的y值跟 contentinset的 top值有关
//        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
//    
//        
//    }
    //移除监听方法
//    override func removeFromSuperview() {
//        superview?.removeObserver(self, forKeyPath: "contentOffset")
//        super.removeFromSuperview()
//    }
    //kvo监听调用方法
//    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        
//        
//        guard let sv = scrollView else {
//            return
//        }
//        
//        let consY = sv.contentOffset.y + 20.0
//        print(consY)
//        if consY == 30.0 {
//            
//        }
//       // contentOffY = sv.contentOffset.y
//        
//    }
}
fileprivate extension HomepageHeaderSectionView{
    func setUpUI(){
        scrollView.contentSize = CGSize(width: ScreenWith * 2, height: self.bounds.height)
        for i  in 0 ..< itemCout {
            
            //行
            var  line = CGFloat(i / 4)
            //列
            var col = CGFloat(i % 4)
            if i >= 8 {
                //行
                line = CGFloat((i - 8) / 4)
                //列
                col = CGFloat((i - 8) % 4 + 4)
            }
            
            
            let item = HomepageItem.loadNib()
            item.frame = CGRect(x: col * itemWith, y: line * itemWith, width: itemWith, height: itemWith)
            item.addTarget(self, action: #selector(itemAct), for: .touchUpInside)
            item.tag = 100 + i
            scrollView.addSubview(item)
        }
        
    }
    @objc func itemAct(item:HomepageItem?){
        
    }
}
